container_max_number=1
docker_project='yzj-data-center-service';
function health_check () {
    # 获取当前运行中容器的总量
    new_container=$(docker ps -aq --filter name=${docker_project} | head -n 1)
    index=1
    echo -e "当前最新的容器为：${new_container}"
    # 获取当前容器的运行状态
    while true
    do
        sleep 2
        # 最多检查 30 次
        if [ "${index}" -eq 30 ];
        then
            echo -e "第 ${index} 次检查，发布失败！！o(≧口≦)o：${cur_container_status}"
            docker logs -f -t "${new_container}" --tail=50
            docker stop "${new_container}" && docker rm "${new_container}"
            exit 1
            break;
        fi

        cur_container_status=$(docker inspect --format="{{json .State.Health}}" "${new_container}" | awk -F'"' '/"Status"/{print $4}')
        # 检查最新的容器状态
        if [ "${cur_container_status}" == "healthy" ];
        then
            echo -e "第 ${index} 次检查成功！！( •̀ ω •́ )✧：${cur_container_status}"
            delete_old_container
            break
        else
            echo -e "第 ${index} 次检查🫡！！：${cur_container_status}"
        fi
        ((index++))
    done
}

function delete_old_container () {
    # 获取当前运行中容器的总量
    cur_container_number=$(docker ps -q --filter name="${docker_project}" | wc -l)
    echo -e "开始替换容器 n=${cur_container_number}"
    if [ "$cur_container_number" -eq ${container_max_number} ];
    then
        echo -e "替换失败: 容器数量已是最小值"
    elif
        [ "$cur_container_number" -gt ${container_max_number} ];
        then
            old_containers=$(docker ps -aq --filter name=${docker_project} | tail -n "$((cur_container_number - container_max_number))")
            echo -e "即将轮替以下容器: ${old_containers}"
            for old_container in ${old_containers}
            do
                docker stop "${old_container}" && docker rm "${old_container}"
                echo -e "删除 ${old_container} 成功😄!!!"
            done
            echo -e "启动成功~~~ <(￣︶￣)↗[GO!]"
    fi
}

echo "--- 删除镜像 ---"
docker rmi ${docker_project} --force;
echo "--- 构造 docker-compose ---"
docker-compose up -d --build --no-recreate --remove-orphans --scale ${docker_project}=$((container_max_number + 1))
echo "--- 检查并切换容器 ---"
health_check
echo "--- 刷新 nginx ---"
docker exec nginx nginx -s reload
echo "--- 清理 none 镜像 ---"
docker images | grep "none" | awk '{print $3}' | xargs -r docker rmi
exit 0